﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using KeanuMvc.Reference;
using HIS.Utils.Securities;
using HIS.Utils;
using HISModels.Entities;
using System.Configuration;
using Newtonsoft.Json.Linq;
using HISModels.ViewModel;

namespace HIS.Controllers.Master
{

    public class SupplierType : HIS.Controllers.AppBaseController
    {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
       
        #endregion

        public SupplierType()
        {
            Data.Add("Pagetitle", "Supplier Type");
            Data.Add("Notification", strNotification);
        }

        [Authorization(RoleAction = "master-suppliers")]
        public override void Index()
        {
            try
            {
                Data["Pagetitle"] += " :: Supplier Type";
                RenderFile("master\\suppliertypelist.html");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        [Authorization(RoleAction = "master-suppliers")]
        public void TableList()
        {
            try
            {

                string strJson = string.Empty;
                string sEcho = HttpContext.Current.Request["sEcho"];

                string code = HttpContext.Current.Request["namevalue"].NullSafeToString();

                string ssearch = "namevalue=" + code;

                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                pagingSearch.sSearch = ssearch;

                string strUri = "";
                strUri = Global.ServiceUriDictionary["suppliertypepage"] + Global.ServiceUriDictionary["requestformat"];
                //strUri = ConfigurationManager.AppSettings["supplierpage"] + ConfigurationManager.AppSettings["requestformat"];
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));


                strJson = stringReader.ReadToEnd();
                stringReader.Dispose();
                base.RestService.Dispose();


                HttpContext.Current.Response.Write(strJson);

            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
        [Authorization(RoleAction = "master-suppliers")]
        public void SupplierTypePrepaireForAdd()
        {
            try
            {
                Data["Pagetitle"] += " :: Add Supplier";
                var newSupplier = new HISModels.Entities.RefSupplierType { Id=0, NameValue="" };


                Data.Add("suppliertype", newSupplier);
             
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {
                RenderFile("master\\suppliertypeedit.html");
                base.RestService.Dispose();
            }

        }

        [Authorization(RoleAction = "master-suppliers")]
        public void SupplierTypePrepaireForEdit()
        {
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            try
            {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            }
            catch
            {
                /// Throw to list if something goes wrong
                GoToUrl("suppliers/"); return;
            }

            try
            {
                Data["Pagetitle"] += " :: Edit Supplier Type";

                //get supplier
                string strUri = Global.ServiceUriDictionary["suppliertype"] + id + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                var suppliertype = JsonConvert.DeserializeObject<HISModels.Entities.RefSupplierType>(stringReader.ReadToEnd());

              




             
                Data.Add("suppliertype", suppliertype);
               
                Data["Notification"] = strNotification;

            }
            catch (Exception ex)
            {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            }
            finally
            {



                RenderFile("master\\suppliertypeedit.html");
                if (stringReader != null) stringReader.Dispose();

                base.RestService.Dispose();
            }

        }

        [Authorization(RoleAction = "master-supplier")]
        public void SaveSupplierType()
        {
            StringReader stringReader = null;
            string strUri = string.Empty;
            int id = 0;
            try
            {
                RefSupplierType suppliertype = new RefSupplierType();
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                Utils.Helper.SetNullToEmptyString(suppliertype);

           
                if(id != 0)
                {
                    strUri = Global.ServiceUriDictionary["suppliertype"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    suppliertype = JsonConvert.DeserializeObject<RefSupplierType>(stringReader.ReadToEnd());
                   
                }

                // get supplier data
                suppliertype.PostHandler<HISModels.Entities.RefSupplierType>();
 

              

                strUri = Global.ServiceUriDictionary["suppliertype"] + Global.ServiceUriDictionary["requestformat"];

                if (id == 0) // new
                {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(suppliertype));
                }
                else //edit
                {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(suppliertype));
                }



                if (stringReader == null)
                {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                    strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + suppliertype.Id + "\"}";

                }
                else
                {


                    string temp = stringReader.ReadToEnd();
                    suppliertype = JsonConvert.DeserializeObject<RefSupplierType>(temp);
                    if (suppliertype == null)
                    {
                        strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + id + "\"}";
                    }
                    else
                    {
                        strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + suppliertype.Id + "\"}";
                    }

                }

            }
            catch (Exception ex)
            {
                strNotification = Helper.ErrorMessage(ex.Message);
                strNotification = "{\"strNotification\": \"" + strNotification + "\", \"id\": \"" + id + "\"}";
            }
            finally
            {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }
        [Authorization(RoleAction = "master-supplier")]
        public void DeleteSupplierType()
        {
            StringReader stringReader = null;
            int id = 0;
            int resultId = 0;  // ok = 1; ko = 0
            try
            {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            }
            catch
            {
                GoToUrl("supplier/");
                return;
            }

            try
            {
                //doctor = new HISModels.Entities.Doctor();
                //string strUri = Data["servicerooturl"] + "sys/actiongroups/?format=json";
                string strUri = Global.ServiceUriDictionary["suppliertype"] + Global.ServiceUriDictionary["requestformat"];

                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));

                if (stringReader == null)
                {
                    //error was here
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                    resultId = 0;
                }
                else
                {
                    string temp = stringReader.ReadToEnd();
                    var result = JsonConvert.DeserializeObject<Supplier>(temp);
                    if (result == null)
                    {
                        strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        resultId = 0;
                    }
                    else
                    {
                        strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                        resultId = 1;
                    }

                }





            }
            catch (Exception ex)
            {
                strNotification = Helper.ErrorMessage(ex.Message);
                resultId = 0;
            }
            finally
            {
                var respondData = JsonConvert.SerializeObject(new { strNotification = strNotification, resultId = resultId });

                HttpContext.Current.Response.Write(respondData);
                base.RestService.Dispose();
            }
        }
    }
}